package com.fastbee.data.controller;

import com.fastbee.common.annotation.Log;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.iot.domain.WhhxDeviceMonitor;
import com.fastbee.iot.domain.WhhxDeviceParameter;
import com.fastbee.iot.service.IMonitorService;
import com.fastbee.iot.service.IParameterService;
import com.fastbee.iot.tdengine.service.model.WhhxDeviceMonitorDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.fastbee.iot.tdengine.service.test.TaosTest;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 设备参数监测Controller
 *
 * @author hejunlong
 * @date 2025-06-25
 */
@Api(tags = "设备参数监测")
@RestController
@RequestMapping("/iot/monitor")
public class MonitorController extends BaseController
{
    @Value("${spring.datasource.dynamic.datasource.taos.url}")
    private String url;

    @Value("${spring.datasource.dynamic.datasource.taos.username}")
    private String username;

    @Value("${spring.datasource.dynamic.datasource.taos.password}")
    private String password;

    @Autowired
    private IMonitorService monitorService;

    @Autowired
    private IParameterService parameterService;

    /**
     * 查询设备参数监测数据
     */
    @GetMapping("/list")
    @ApiOperation("查询设备参数监测列表")
//    @PreAuthorize("@ss.hasPermi('iot:monitor:list')")
    public TableDataInfo list(WhhxDeviceMonitor whhxDeviceMonitor)
    {
        startPage();
        // 1. 查询设备监测数据列表
        List<WhhxDeviceMonitor> monitorList = monitorService.selectDeviceMonitorList(whhxDeviceMonitor);

        // 2. 获取所有参数编码（去重）
        Set<String> paramCodes = monitorList.stream()
                .map(WhhxDeviceMonitor::getParmaterCode)
                .collect(Collectors.toSet());

        // 3. 批量查询参数阈值（Map结构，key=paramCode）
        Map<String, WhhxDeviceParameter> paramThresholdMap = parameterService.selectParameterByCodes(paramCodes)
                .stream()
                .collect(Collectors.toMap(WhhxDeviceParameter::getCode, Function.identity()));

        // 4. 遍历监测数据，判断是否预警
        monitorList.forEach(monitor -> {
            String paramCode = monitor.getParmaterCode();
            String currentValueStr = monitor.getParmaterValue();  // 当前监测值（String）

            if (paramCode == null || currentValueStr == null) {
                monitor.setAlarm("参数编码或当前监测值为空");
                return;
            }

            WhhxDeviceParameter parameter = paramThresholdMap.get(paramCode);
            if (parameter == null) {
                monitor.setAlarm("参数编码不存在");
                return;
            }

            String minThresholdStr = parameter.getParameterMin();  // 最小阈值（String）
            String maxThresholdStr = parameter.getParameterMax();  // 最大阈值（String）

            try {
                // 转换为 Double 类型
                Double currentValue = Double.parseDouble(currentValueStr);
                Double minThreshold = (minThresholdStr != null) ? Double.parseDouble(minThresholdStr) : null;
                Double maxThreshold = (maxThresholdStr != null) ? Double.parseDouble(maxThresholdStr) : null;

                // 判断是否预警
                if (minThreshold != null && maxThreshold != null) {
                    if (currentValue < minThreshold || currentValue > maxThreshold) {
                        monitor.setAlarm("超出阈值范围");
                    } else {
                        monitor.setAlarm("正常");
                    }
                } else {
                    monitor.setAlarm("正常");
                }
            } catch (NumberFormatException e) {
                // 如果转换失败（如字符串不是有效数字），标记为"未知"
                monitor.setAlarm("未知");
            }
            monitorService.updateMonitor(monitor);
        });
        // 5. 返回分页数据
        return getDataTable(monitorList);

//        TableDataInfo dataTable = getDataTable(monitorService.selectDeviceMonitorList(whhxDeviceMonitor));
//        return getDataTable(monitorService.selectDeviceMonitorList(whhxDeviceMonitor));
    }

    /**
     * 查询设备参数监测数据
     */
//    @GetMapping("/listTaos")
//    @ApiOperation("查询Taos设备参数监测列表")
//    public TableDataInfo listTaos(WhhxDeviceMonitor whhxDeviceMonitor){
//        startPage();
//        TaosTest taosTest = new TaosTest();
//        List<WhhxDeviceMonitor> whhxDeviceMonitors = taosTest.test1(whhxDeviceMonitor);
//        System.out.println(whhxDeviceMonitors);
//        return getDataTable(whhxDeviceMonitors);
//    }



    /**
     * 查询设备参数监测数据
     */
//    @GetMapping("/listTaos")
//    @ApiOperation("查询Taos设备参数监测列表")
//    public TableDataInfo listTaos(WhhxDeviceMonitor whhxDeviceMonitor){
//        TaosTest taosTest = new TaosTest();
//        List<WhhxDeviceMonitor> allMonitors = taosTest.test1(whhxDeviceMonitor);
//
//        // 使用 Spring Data Commons 的 Pageable 来实现分页
//        Pageable pageable = PageRequest.of(whhxDeviceMonitor.getPageNum() - 1, whhxDeviceMonitor.getPageSize());
//        List<WhhxDeviceMonitor> pageMonitors = allMonitors.stream()
//                .skip(pageable.getOffset())
//                .limit(pageable.getPageSize())
//                .collect(Collectors.toList());
//        return getTaosDataTable(pageMonitors,allMonitors.size());
//
//    }


    /**
     * 查询设备参数监测数据
     */
    @GetMapping("/listTaos")
    @ApiOperation("查询Taos设备参数监测列表")
    public TableDataInfo listTaos(WhhxDeviceMonitorDTO whhxDeviceMonitorDTO){
        TaosTest taosTest = new TaosTest();
        System.out.println("11111111111111111111111"+url + username + password);
        return taosTest.tableDataInfo(whhxDeviceMonitorDTO,url,username,password);
//        List<WhhxDeviceMonitor> allMonitors = taosTest.test1(whhxDeviceMonitorDTO, url, username, password);

        // 使用 Spring Data Commons 的 Pageable 来实现分页
//        Pageable pageable = PageRequest.of(whhxDeviceMonitorDTO.getPageNum() - 1, whhxDeviceMonitorDTO.getPageSize());

        // 应用前端查询条件过滤结果
//        List<WhhxDeviceMonitor> filteredMonitors = allMonitors.stream()
//                .filter(monitor -> {
//                    // 时间范围过滤
//                    // 定义时间格式（必须与 String 格式完全一致）
//                    final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//                    if (whhxDeviceMonitorDTO.getStartTime() != null && whhxDeviceMonitorDTO.getEndTime() != null) {
//                        LocalDateTime monitorTime = monitor.getMonitorTime();
//                        try {
//                            // 将 String 转换为 LocalDateTime
//                            LocalDateTime startTime = LocalDateTime.parse(whhxDeviceMonitorDTO.getStartTime(), DATE_TIME_FORMATTER);
//                            LocalDateTime endTime = LocalDateTime.parse(whhxDeviceMonitorDTO.getEndTime(), DATE_TIME_FORMATTER);
//
//                            if (monitorTime == null || monitorTime.isBefore(startTime) || monitorTime.isAfter(endTime)) {
//                                return false;
//                            }
//                        } catch (DateTimeParseException e) {
//                            // 处理时间格式错误（如日志记录或抛出异常）
//                            System.err.println("时间格式错误!");
//                            return false;
//                        }
//                    }
//
//                    // 预警状态过滤
//                    if (whhxDeviceMonitorDTO.getAlarmStatus() != null) {
//                        String alarmStatus = whhxDeviceMonitorDTO.getAlarmStatus();
//                        if (!alarmStatus.isEmpty()) {
//                            if ("正常".equals(alarmStatus) && !"正常".equals(monitor.getAlarm())) {
//                                return false;
//                            }
//                            if ("预警".equals(alarmStatus) && !"超出阈值范围".equals(monitor.getAlarm())) {
//                                return false;
//                            }
//                            if ("预警".equals(alarmStatus) && !"参数不存在".equals(monitor.getAlarm())) {
//                                return false;
//                            }
//                        }
//                    }
//
//                    // 参数名称模糊查询
//                    if (whhxDeviceMonitorDTO.getParameterNameQuery() != null &&
//                            !whhxDeviceMonitorDTO.getParameterNameQuery().isEmpty()) {
//                        String paramName = monitor.getParmaterName();
//                        if (paramName == null || !paramName.contains(whhxDeviceMonitorDTO.getParameterNameQuery())) {
//                            return false;
//                        }
//                    }
//
//                    // 参数编码模糊查询
//                    if (whhxDeviceMonitorDTO.getParameterCodeQuery() != null &&
//                            !whhxDeviceMonitorDTO.getParameterCodeQuery().isEmpty()) {
//                        String paramCode = monitor.getParmaterCode();
//                        if (paramCode == null || !paramCode.contains(whhxDeviceMonitorDTO.getParameterCodeQuery())) {
//                            return false;
//                        }
//                    }
//
//                    return true;
//                })
//                .collect(Collectors.toList());
//
//        // 分页处理
//        List<WhhxDeviceMonitor> pageMonitors = filteredMonitors.stream()
//                .skip(pageable.getOffset())
//                .limit(pageable.getPageSize())
//                .collect(Collectors.toList());
//
//        return getTaosDataTable(pageMonitors, filteredMonitors.size());

    }


    /**
     * 查询设备参数监测设备状态数据
     */
    @GetMapping("/listStatus")
    @ApiOperation("查询Taos设备参数监测设备状态")
    public AjaxResult listTaosStatus(WhhxDeviceMonitorDTO whhxDeviceMonitorDTO){
        TaosTest taosTest = new TaosTest();
        List<WhhxDeviceMonitor> latestDeviceStatus = taosTest.getLatestDeviceStatus(whhxDeviceMonitorDTO.getDeviceCode(), url, username, password);
        if (latestDeviceStatus != null) {
            // 使用 Stream 查找 MN39 参数
            Optional<WhhxDeviceMonitor> MonitorOpt = latestDeviceStatus.stream()
                    .filter(m -> "MN39".equals(m.getParmaterCode()))
                    .findFirst();
            System.out.println(MonitorOpt);
            return AjaxResult.success(MonitorOpt);
        }
        return AjaxResult.error("无数据");
    }

    /**
     * 查询设备参数监测数据（返回全部数据，用于导出）
     */
    @GetMapping("/listTaosAll")
    @ApiOperation("查询Taos设备参数监测列表（全部数据）")
    public List<WhhxDeviceMonitor> listTaosAll(WhhxDeviceMonitorDTO whhxDeviceMonitorDTO) {
        TaosTest taosTest = new TaosTest();
        System.out.println("查询参数：" + url + username + password);

        // 1. 查询所有数据（不带分页）
        List<WhhxDeviceMonitor> allMonitors = taosTest.test1(whhxDeviceMonitorDTO, url, username, password);

        // 2. 应用前端查询条件过滤结果
        List<WhhxDeviceMonitor> filteredMonitors = allMonitors.stream()
                .filter(monitor -> {
                    // 时间范围过滤
                    final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    if (whhxDeviceMonitorDTO.getStartTime() != null && whhxDeviceMonitorDTO.getEndTime() != null) {
                        LocalDateTime monitorTime = monitor.getMonitorTime();
                        try {
                            LocalDateTime startTime = LocalDateTime.parse(whhxDeviceMonitorDTO.getStartTime(), DATE_TIME_FORMATTER);
                            LocalDateTime endTime = LocalDateTime.parse(whhxDeviceMonitorDTO.getEndTime(), DATE_TIME_FORMATTER);

                            if (monitorTime == null || monitorTime.isBefore(startTime) || monitorTime.isAfter(endTime)) {
                                return false;
                            }
                        } catch (DateTimeParseException e) {
                            System.err.println("时间格式错误!");
                            return false;
                        }
                    }

                    // 预警状态过滤
                    if (whhxDeviceMonitorDTO.getAlarmStatus() != null && !whhxDeviceMonitorDTO.getAlarmStatus().isEmpty()) {
                        String alarmStatus = whhxDeviceMonitorDTO.getAlarmStatus();
                        if ("正常".equals(alarmStatus) && !"正常".equals(monitor.getAlarm())) {
                            return false;
                        }
                        if ("预警".equals(alarmStatus) && !"超出阈值范围".equals(monitor.getAlarm()) && !"参数不存在".equals(monitor.getAlarm())) {
                            return false;
                        }
                    }

                    // 参数名称模糊查询
                    if (whhxDeviceMonitorDTO.getParameterNameQuery() != null && !whhxDeviceMonitorDTO.getParameterNameQuery().isEmpty()) {
                        String paramName = monitor.getParmaterName();
                        if (paramName == null || !paramName.contains(whhxDeviceMonitorDTO.getParameterNameQuery())) {
                            return false;
                        }
                    }

                    // 参数编码模糊查询
                    if (whhxDeviceMonitorDTO.getParameterCodeQuery() != null && !whhxDeviceMonitorDTO.getParameterCodeQuery().isEmpty()) {
                        String paramCode = monitor.getParmaterCode();
                        if (paramCode == null || !paramCode.contains(whhxDeviceMonitorDTO.getParameterCodeQuery())) {
                            return false;
                        }
                    }

                    return true;
                })
                .collect(Collectors.toList());

        // 3. 直接返回过滤后的全部数据（不分页）
        return filteredMonitors;
    }

}
